package thirdDay;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

public class threeSum {
    public static void main(String[] args) {
        int[] nums = {};

    }

    public static List<List<Integer>> threeSumMethod(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        if (nums.length == 3){
            if (Arrays.stream(nums).sum() == 0) {
                List<Integer> temp = new ArrayList<>();
                temp.add(nums[0]);
                temp.add(nums[1]);
                temp.add(nums[2]);
                ans.add(temp);
            }
            return ans;
        } else if (nums.length < 3) {
            return ans;
        }
        nums = Arrays.stream(nums).sorted().toArray();
        int start,end;
        int target = nums.length - 1;

        for (int i = target; i > 1; i--) {
            if (i < target && nums[i] == nums[i + 1]){
                continue;
            }
            start = 0;
            end = i - 1;
            while (start < end){
                if (nums[start] + nums[end] + nums[i] == 0){
                    List<Integer> temp_list = new ArrayList<>();
                    temp_list.add(nums[start]);
                    temp_list.add(nums[end]);
                    temp_list.add(nums[i]);
                    ans.add(temp_list);
                    while (nums[start] == nums[start+1]){
                        start++;
                    }
                    while (nums[end] == nums[end-1]){
                        end--;
                    }
                } else if (nums[start] + nums[end] + nums[i] < 0) {
                    while (nums[start] == nums[start+1]){
                        start++;
                    }
                } else {
                    while (nums[end] == nums[end-1]){
                        end--;
                    }
                }
            }
        }
        List<List<Integer>> listWithoutDuplicates = ans.stream().distinct().collect(Collectors.toList());
        return listWithoutDuplicates;
    }
}
